package com.vancouver.knows.ui.activity.userpost;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.util.Pair;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.ToggleButton;

import com.alibaba.fastjson.JSON;
import com.pangu.service.ActionException;
import com.pangu.task.IResultReceiver;
import com.pangu.task.mark.ATaskMark;
import com.pangu.util.StringUtil;
import com.squareup.picasso.Picasso;
import com.vancouver.knows.R;
import com.vancouver.knows.business.bean.CategoryInfo;
import com.vancouver.knows.business.bean.FilterArgs;
import com.vancouver.knows.business.bean.SubcategoryInfo;
import com.vancouver.knows.business.service.impl.FetchUserPostCategoriesHandler;
import com.vancouver.knows.business.task.mark.FetchUserPostCategoriesTaskMark;
import com.vancouver.knows.business.task.mark.FetchUserPostsTaskMark;
import com.vancouver.knows.ui.base.BaseActivity;
import com.vancouver.knows.ui.view.FlowLayout;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Set;
import java.util.TreeSet;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * Created by Chris Li on 2016-07-13.
 */
public class UserPostFilterActivity extends BaseActivity implements IResultReceiver {

    public static final String BUY_AND_SELL_SLUG = "buy-and-sell";
    public static final String MUTUAL_SUPPORT_SLUG = "mutual-support";
    public static final String FRIENDS_AND_PARTNERS_SLUG = "friends-and-partners";
    public static final String HOUSING_SLUG = "housing";
    public static final String JOBS_SLUG = "jobs";

    public static final int FILTER_REQUEST = 369;
    public static final String SELECTED_CATEGORIES_EXTRA = "selected_categories";

    @Bind(R.id.category_recycler_view)
    RecyclerView mCategoryRecyclerView;
    @Bind(R.id.loading_view)
    RelativeLayout mLoadingView;

    private CategoryAdapter mCategoryAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_user_post_filter);

        mCategoryRecyclerView.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false));
        mCategoryAdapter = new CategoryAdapter(this, new ArrayList<Object>());
        mCategoryRecyclerView.setAdapter(mCategoryAdapter);

        HashMap categoryMap = imContext.getBusinessModule().getCacheManager().getUserPostCategories();
        if (!categoryMap.isEmpty()) {
            setCategoryData(categoryMap);
        } else {
            imContext.getBusinessModule().getServiceWrapper().fetchUserPostCategories(this, new FetchUserPostCategoriesTaskMark());
        }
    }

    @OnClick(R.id.back_icon)
    public void onBackButtonClicked() {
        onBackPressed();
    }

    @OnClick(R.id.reset_icon)
    public void onResetButtonClicked() {
        mCategoryAdapter.clearSelectedCategories();
    }

    @OnClick(R.id.go_button)
    public void onGoButtonClicked() {
        Intent intent = new Intent();
        intent.putExtra(SELECTED_CATEGORIES_EXTRA, mCategoryAdapter.getSelectedCategories());
        setResult(RESULT_OK, intent);
        finish();
    }

    @Override
    public void receiveResult(ATaskMark taskMark, ActionException exception, Object trackerResult) {

        if (exception != null) {
            Log.e(TAG, exception.getExMessage());
        }

        HashMap categoryMap = imContext.getBusinessModule().getCacheManager().getUserPostCategories();
        if (categoryMap != null) {
            setCategoryData(categoryMap);
        }
    }

    private void setCategoryData(HashMap categoryMap) {

        mLoadingView.setVisibility(View.GONE);

        List<CategoryInfo> categoryInfoList = (List<CategoryInfo>) categoryMap.get(FetchUserPostCategoriesHandler.USERPOST_CATEGORIES);
        List<String> cityList = (List<String>) categoryMap.get(FetchUserPostCategoriesHandler.CITY_LIST);
        String cityListImage = (String) categoryMap.get(FetchUserPostCategoriesHandler.CITY_LIST_IMAGE);

        List categoryList = new ArrayList();
        categoryList.addAll(categoryInfoList);
        categoryList.add(new Pair<>(getApplication().getString(R.string.area_limit), cityList));

        // check to see if filter was applied
        FetchUserPostsTaskMark fetchUserPostsTaskMark = imContext.getBusinessModule().getTaskMarkPool().getFetchUserPostsTaskMark();
        if (!StringUtil.isEmptyString(fetchUserPostsTaskMark.getFilter())) {
            String filterJsonString = fetchUserPostsTaskMark.getFilter();
            FilterArgs filterArgs = JSON.toJavaObject(JSON.parseObject(filterJsonString), FilterArgs.class);
            if (filterArgs != null) {
                HashMap<String, Set<String>> chosenCategories = new HashMap<>();
                for (FilterArgs.Category category : filterArgs.getCategories()) {
                    if (category.getSubcategories() != null) {
                        chosenCategories.put(category.getCategory(), category.getSubcategories());
                    } else {
                        Set<String> subcategories = new TreeSet<String>();
                        subcategories.add("");
                        chosenCategories.put(category.getCategory(), subcategories);
                    }
                }

                if (filterArgs.getCities() != null) {
                    chosenCategories.put("cities", new TreeSet<String>(filterArgs.getCities()));
                } else {
                    Set<String> cities = new TreeSet<>();
                    cities.add("");
                    chosenCategories.put("cities", cities);
                }

                mCategoryAdapter.setSelectedCategories(chosenCategories);
            }
        }

        mCategoryAdapter.addItems(categoryList, cityListImage);
    }


    public static class CategoryAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> implements CompoundButton.OnCheckedChangeListener {

        private LayoutInflater mLayoutInflater;
        private List<Object> mCategories;
        private String mCityListImage;
        private HashMap<String, Set<String>> mChosenCategories = new HashMap<>();

        public CategoryAdapter(Context context, List<Object> list) {
            this.mLayoutInflater = LayoutInflater.from(context);
            this.mCategories = list;
        }

        @Override
        public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            View view = mLayoutInflater.inflate(R.layout.category_view_item, parent, false);
            return new CategoryViewHolder(view);
        }

        @Override
        public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
            Object object = mCategories.get(position);
            CategoryViewHolder categoryViewHolder = (CategoryViewHolder) holder;

            if (object instanceof CategoryInfo) {
                CategoryInfo categoryInfo = (CategoryInfo) object;
                categoryViewHolder.categoryTitle.setText(categoryInfo.getName());

                categoryViewHolder.subcategoriesContainer.removeAllViews();
                List<SubcategoryInfo> subcategoryInfoList = categoryInfo.getSubcategories();
                for (SubcategoryInfo subcategoryInfo : subcategoryInfoList) {
                    ToggleButton toggleButton = (ToggleButton) mLayoutInflater.inflate(R.layout.tag_toggle_layout, categoryViewHolder.subcategoriesContainer, false);
                    toggleButton.setText(subcategoryInfo.getName());
                    toggleButton.setTextOn(subcategoryInfo.getName());
                    toggleButton.setTextOff(subcategoryInfo.getName());
                    toggleButton.setTag(new Pair<>(categoryInfo.getSlug(), subcategoryInfo.getSlug()));

                    if (isCategoryChosen(categoryInfo.getSlug(), subcategoryInfo.getSlug())){
                        toggleButton.setChecked(true);
                    }

                    toggleButton.setOnCheckedChangeListener(this);
                    categoryViewHolder.subcategoriesContainer.addView(toggleButton, new FlowLayout.LayoutParams(25, 25));
                }

//                int drawableResId = 0;
//                switch (categoryInfo.getSlug()) {
//
//                    case UserPostFilterActivity.BUY_AND_SELL_SLUG:
//                        drawableResId = R.drawable.price_tag;
//                        break;
//
//                    case UserPostFilterActivity.FRIENDS_AND_PARTNERS_SLUG:
//                        drawableResId = R.drawable.conference_call;
//                        break;
//
//                    case UserPostFilterActivity.HOUSING_SLUG:
//                        drawableResId = R.drawable.interior;
//                        break;
//
//                    case UserPostFilterActivity.JOBS_SLUG:
//                        drawableResId = R.drawable.find_user;
//                        break;
//
//                    case UserPostFilterActivity.MUTUAL_SUPPORT_SLUG:
//                        drawableResId = R.drawable.helping_hand;
//                        break;
//
//                }
                String imageUrl = categoryInfo.getImageUrl();
                if (!StringUtil.isEmptyString(imageUrl)) {
                    Picasso.with(categoryViewHolder.itemView.getContext())
                            .load(imageUrl)
                            .into(categoryViewHolder.categoryIcon);
                }

            } else if (object instanceof Pair) {
                Pair pair = (Pair) object;
                categoryViewHolder.categoryTitle.setText((String) pair.first);

                categoryViewHolder.subcategoriesContainer.removeAllViews();
                List<String> cityList = (List<String>) pair.second;
                for (String city : cityList) {
                    ToggleButton toggleButton = (ToggleButton) mLayoutInflater.inflate(R.layout.tag_toggle_layout, categoryViewHolder.subcategoriesContainer, false);
                    toggleButton.setText(city);
                    toggleButton.setTextOn(city);
                    toggleButton.setTextOff(city);
                    toggleButton.setTag(new Pair<>("cities", city));

                    if (isCityChosen(city)) {
                        toggleButton.setChecked(true);
                    }

                    toggleButton.setOnCheckedChangeListener(this);
                    categoryViewHolder.subcategoriesContainer.addView(toggleButton, new FlowLayout.LayoutParams(25, 25));
                }

                Picasso.with(categoryViewHolder.itemView.getContext())
                        .load(mCityListImage) //R.drawable.marker
                        .into(categoryViewHolder.categoryIcon);

            }
        }

        private boolean isCategoryChosen(String category, String subcategory) {
            if (mChosenCategories.containsKey(category)) {
                Set<String> chosenSubcategories = mChosenCategories.get(category);
                if (chosenSubcategories.contains(subcategory)) {
                    return true;
                }
            }

            return false;
        }

        private boolean isCityChosen(String city) {
            if (mChosenCategories.containsKey("cities")) {
                Set<String> chosenSubcategories = mChosenCategories.get("cities");
                if (city.equals("全部")) {
                    return true;
                }

                if (chosenSubcategories.contains(city)) {
                    return true;
                }
            }

            return false;
        }

        @Override
        public int getItemCount() {
            return mCategories.size();
        }

        public void addItems(List<Object> objectList, String cityListImage) {
            this.mCategories.addAll(objectList);
            this.mCityListImage = cityListImage;
            notifyDataSetChanged();
        }

        @Override
        public void onCheckedChanged(CompoundButton compoundButton, boolean selected) {

            Pair pair = (Pair) compoundButton.getTag();
            String chosenCategory = (String) pair.first;
            String chosenSubcategory = (String) pair.second;
            if (selected) {
                if (!mChosenCategories.containsKey(chosenCategory)) {
                    Set<String> subcategories = new TreeSet<>();
                    if (chosenSubcategory.equals("全部") && chosenCategory.equals("cities")) {
                        subcategories.add("");
                    } else {
                        subcategories.add(chosenSubcategory);
                    }
                    mChosenCategories.put(chosenCategory, subcategories);
                } else {
                    Set<String> chosenSubcategories = mChosenCategories.get(chosenCategory);

                    if (chosenSubcategory.isEmpty() || chosenSubcategory.equals("全部")) {
                        chosenSubcategories.clear();
                        chosenSubcategories.add("");
                    } else {
                        chosenSubcategories.remove("");
                        chosenSubcategories.add(chosenSubcategory);
                    }

                    mChosenCategories.put(chosenCategory, chosenSubcategories);
                    notifyDataSetChanged();
                }
            } else {
                Set<String> chosenSubcategories = mChosenCategories.get(chosenCategory);
                chosenSubcategories.remove(chosenSubcategory);
                mChosenCategories.put(chosenCategory, chosenSubcategories);
            }
        }

        public HashMap<String, Set<String>> getSelectedCategories() {
            return mChosenCategories;
        }

        public void setSelectedCategories(HashMap<String, Set<String>> chosenCategories) {
            this.mChosenCategories = chosenCategories;
        }

        public void clearSelectedCategories() {
            this.mChosenCategories.clear();
            notifyDataSetChanged();
        }

        public static class CategoryViewHolder extends RecyclerView.ViewHolder {

            @Bind(R.id.category_icon)
            ImageView categoryIcon;
            @Bind(R.id.category_title)
            TextView categoryTitle;
            @Bind(R.id.subcategories_container)
            FlowLayout subcategoriesContainer;

            public CategoryViewHolder(View itemView) {
                super(itemView);
                ButterKnife.bind(this, itemView);
            }
        }
    }

}
